<template>
  <div
    class="Detail_business"
    :class="permissionVerification('edit', detailType) ? 'business_bottom' : ''"
  >
    <PullRefresh
      class="shopInfo-detail detail"
      v-model="refreshing"
      @refresh="onRefresh"
      pull-distance="0"
    >
      <List
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :immediate-check="false"
      >
        <div>
          <div v-for="(v, i) in list" :key="i" class="info">
            <h4 class="flex justify-between pb-12px items-center">
              <div class="name">{{ v.storeName }}</div>
              <div>
                <Button
                  v-if="permissionVerification('edit', detailType)"
                  size="mini"
                  @click="edit(v.id, (type = '编辑'))"
                  style="width: 64px; padding: 0; height: 25px"
                  ><div class="flex">
                    <img
                      src="../../../assets/business/icon_bj.png"
                      alt=""
                      width="14px"
                      height="14px"
                      class="mr-6px"
                    /><span>编辑</span>
                  </div></Button
                >
              </div>
            </h4>
            <div class="box">
              <span class="inline-block mr-4px name_text">店铺地址：</span>
              <span class="text">{{ v.storeAddress }}</span>
            </div>
            <div class="box">
              <span class="inline-block mr-4px name_text">店铺 POI：</span>
              <span class="text">{{ v.storePoi }}</span>
            </div>
            <div class="box">
              <span class="inline-block mr-4px name_text">联系电话：</span>
              <span class="text">{{ v.storePhone }}</span>
            </div>
            <div class="box">
              <span class="inline-block mr-4px name_text">创建人员：</span>
              <span class="text"> {{ v.createUsername }}</span>
              <span v-if="v.createUserJobNo" class="text"
                >({{ v.createUserJobNo }})</span
              >
            </div>
            <div class="box pb-12px">
              <span class="inline-block mr-4px name_text">创建时间：</span>
              <span class="text">{{ v.createTime }}</span>
            </div>
            <div style="display: flex; justify-content: space-around">
              <div
                v-if="
                  permissionVerification('edit', detailType) &&
                  (v.businessOpportunityStatus === 1 ||
                    v.businessOpportunityStatus === 2)
                "
                @click="del(v.id)"
                class="del"
              >
                <button>删除店铺</button>
              </div>
              <div
                v-if="
                  permissionVerification('edit', detailType) //注释内容加在这里
                "
                @click="trans(v.id, 'searchKey')"
                class="trans"
              >
                <!-- &&  
                (v.businessOpportunityStatus === 1 || 
                  v.businessOpportunityStatus === 2)//为什么商机状态需要是待跟进和跟进中？ -->
                <button>转移店铺</button>
              </div>
            </div>
          </div>
        </div>
      </List>
    </PullRefresh>
    <div v-if="permissionVerification('edit', detailType)" class="add">
      <Button type="info" @click="edit(null, (type = '新增'))" block
        >新增店铺</Button
      >
    </div>
    <ActionSheet
      v-model="editShow"
      :title="title"
      :closeable="false"
      class="edit_shop my_form"
    >
      <van-form
        :show-error-message="false"
        :show-error="false"
        ref="form"
        class="safePadding"
        label-width="62"
      >
        <van-field
          v-model="editFrom.storeName"
          name="店铺名称"
          label="店铺名称"
          placeholder="店铺名称"
          :rules="[{ required: true, message: '请填写店铺名称' }]"
          :class="editFrom.storeName ? 'exist_value' : ''"
        />
        <van-field
          v-model="editFrom.storeAddress"
          right-icon="location-o"
          name="店铺地址"
          label="店铺地址"
          placeholder="店铺地址"
          disabled
          :rules="[{ required: true, message: '请填写店铺地址' }]"
          :class="editFrom.storeAddress ? 'exist_value' : ''"
          @click="() => (showVisitLocation = true)"
        />
        <!-- disabled -->
        <!-- @click="() => (showVisitLocation = true)" -->
        <van-field
          v-model="editFrom.storePoi"
          name="店铺POI"
          label="店铺POI"
          placeholder="店铺POI"
          :rules="[{ required: true, message: '请填写店铺POI' }]"
          :class="editFrom.storePoi ? 'exist_value' : ''"
        />
        <van-field
          v-model="editFrom.storePhone"
          name="联系电话"
          label="联系电话"
          placeholder="联系电话"
          :rules="[{ required: true, message: '请填写联系电话' }]"
          :class="editFrom.storePhone ? 'exist_value' : ''"
        />
        <van-field
          v-if="showUploader"
          :show-arrow="false"
          filed="photos"
          label="门头照"
          :rules="[
            {
              required: type === '新增' ? false : true,
              message: '请上传门头照',
            },
          ]"
          :class="photoList.length > 0 ? 'exist_value' : ''"
          class="height_auto end_field"
        >
          <template #input>
            <LlUploader
              v-model="photoList"
              @input="_onUploadChange"
              @change="_onUploadChange"
            />
          </template>
        </van-field>
        <PopupAction @confirm="editSubmit" @cancel="editShow = false" />
      </van-form>
    </ActionSheet>

    <ActionSheet
      v-model="transferShow"
      :title="'转移店铺'"
      :closeable="false"
      class="edit_shop my_form"
      ><van-form
        :show-error-message="false"
        :show-error="false"
        ref="transForm"
        class="safePadding"
        label-width="62"
      >
        <van-field
          readonly
          v-model="editFrom.storeName"
          name="店铺名称"
          label="店铺名称"
          placeholder="店铺名称"
          :rules="[{ required: true, message: '请填写店铺名称' }]"
          :class="editFrom.storeName ? 'exist_value' : ''"
        />
        <van-field
          readonly
          v-model="editFrom.storeAddress"
          right-icon="location-o"
          name="店铺地址"
          label="店铺地址"
          placeholder="店铺地址"
          disabled
          :rules="[{ required: true, message: '请填写店铺地址' }]"
          :class="editFrom.storeAddress ? 'exist_value' : ''"
        />
        <div class="opportunity_box">
          <SeachSelect
            @changeInputVal="changeInputVal"
            :id="editFrom.id"
            label="转移商机"
            ref="selectionsBD"
            :clear="transferShow"
          >
          </SeachSelect>
        </div>
      </van-form>
      <PopupAction @confirm="transferSubmit" @cancel="transferShow = false" />
    </ActionSheet>

    <actionPopup
      ref="actionPopup"
      @confirm="confirmBut(type)"
      :content="actionP.content"
      :showButtons="actionP.showButtons"
      :confirmText="actionP.confirmText"
      :title="actionP.title"
      :backText="actionP.backText"
      :cancelText="actionP.cancelText"
      @back="back"
    ></actionPopup>
    <!-- 拜访地点 -->
    <Popup v-model="showVisitLocation" position="right">
      <LlMap
        v-if="showVisitLocation"
        @cancel="showVisitLocation = false"
        @confirm="_mapConfirm"
        type="search"
      />
    </Popup>
  </div>
</template>

<script>
import {
  storeShop,
  storeEdit,
  storeAdd,
  storeDel,
  storeCheck,
  storeDetail,
  storeBusinessOpportunity,
  storeTransfer,
  bindTemp,
} from "@/services/business/HighSeas.js";
import {
  Button,
  PullRefresh,
  ActionSheet,
  Form,
  Field,
  List,
  Toast,
  Popup,
  Picker,
} from "vant";
import LlMap from "@/components/ll-map";
import PopupAction from "@/views/business/components/popup_action.vue";
import actionPopup from "@/components/ll-action-popup";
import LlUploader from "@/components/ll-uploader";
import SeachSelect from "./opportunity.vue";
import Bus from "@/config/evenrBus";
import { permissionVerification } from "@/utils/tools";
export default {
  components: {
    Button,
    PullRefresh,
    ActionSheet,
    List,
    LlUploader,
    actionPopup,
    PopupAction,
    [Form.name]: Form,
    [Field.name]: Field,
    LlMap,
    Popup,
    Picker,
    SeachSelect,
  },
  props: {
    detailType: {
      type: String,
      default: "",
    },
    showUploader: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      editShow: false,
      transferShow: false,
      id: null,
      title: "",
      list: [],
      value: "", //测试数据
      actionP: {
        content: "",
        showButtons: "operate",
        confirmText: "",
        title: "",
        backText: "",
        cancelText: "取消",
      },
      editFrom: {},
      photoList: [],
      type: null, //1 删除店铺   2 公海移入临时库
      loading: false,
      refreshing: false,
      finished: false,
      storeId: null,
      showVisitLocation: false,
      tag: true,
      permissionVerification: permissionVerification,
    };
  },

  methods: {
    change(val) {
      this.id = val;
      this.onRefresh();
    },
    _onUploadChange(files) {
      this.editFrom.files = files.map(
        ({ fileName, url, originalName, suffix }) => {
          return {
            fileName,
            name: originalName,
            completeUrl: url,
            suffix,
          };
        }
      );
    },
    // 删除店铺
    del(id) {
      this.storeId = id;
      console.log(id, "id1111");
      this.type = 1;
      this.storeCheck(2, "删除");
    },
    // 转移店铺
    trans(id, searchKey) {
      this.storeId = id;
      this.transferShow = true;
      this.storeDetail(id);
      this.storeBusinessOpportunity(searchKey); //转移店铺可用商机列表
    },
    // 转移商机id选择
    changeInputVal(val) {
      this.value = val;
      console.log("BDdata", this.value);
    },
    //校验编辑  删除 次数弹窗
    storeCheck(val, type, id) {
      let formData = new FormData();
      formData.append("type", val);
      storeCheck(formData)
        .then((res) => {
          if (res && res.code) {
            Toast(res.message);
          } else {
            //编辑店铺信息
            if (type === "编辑") {
              this.editShow = true;
              console.log(id);
              this.storeDetail(id);
              //删除店铺操作
            } else if (type === "删除") {
              this.actionP.title = "删除店铺";
              this.actionP.content = "您确认要删除店铺吗？";
              this.actionP.confirmText = "确认删除";
              this.actionP.cancelText = "取消";
              this.actionP.showButtons = "operate";
              this.$nextTick(() => {
                this.$refs.actionPopup.open(this.actionP);
              });
            }
          }
        })
        .catch((err) => {
          let { code, message } = err;
          if (code === 1000) {
            this.actionP.title = "";
            this.actionP.content = message;
            this.actionP.showButtons = "back";
            this.actionP.backText = "返回";
            this.$nextTick(() => {
              this.$refs.actionPopup.open(this.actionP);
            });
            return;
          } else {
            Toast(err.errMessage || err.message);
          }
        });
    },
    //删除店铺确认按钮
    confirmBut(val) {
      if (!this.tag) return;
      this.tag = false;
      console.log("555");
      if (val === 1) {
        // console.log(this.actionP);
        let formData = new FormData();
        formData.append("id", this.storeId);
        storeDel(formData)
          .then((res) => {
            this.tag = true;
            if (res && res.code != 200) {
              Toast(res.message);
            } else {
              this.$nextTick(() => {
                this.getData();
              });
            }
          })
          .catch((err) => {
            this.tag = true;
            Toast(err.errMessage || err.message);
          });
      } else if (val === 2) {
        bindTemp(this.id)
          .then((res) => {
            this.tag = true;
            this.editShow = false;
          })
          .catch((err) => {
            this.tag = true;
            Toast(err.errMessage || err.message);
          });
      }
      this.$refs.actionPopup.close();
    },

    // 确认新增
    editSubmit() {
      this.$refs.form
        .validate()
        .then(() => {
          // let reg =
          //   /0\d{2,3}-\d{7,8}|\(?0\d{2,3}[)-]?\d{7,8}|\(?0\d{2,3}[)-]*\d{7,8}/;
          // let reg2 =
          //   /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
          let reg = /^\d+([\,\-]\d+)*$/;
          if (!reg.test(this.editFrom.storePhone)) {
            Toast("电话组成只能为数字和“-”，电话与电话之间使用英文“,”隔开！");
            return;
          }
          if (!this.tag) return;
          this.tag = false;
          let parmas = {
            id: this.editFrom.id,
            businessOpportunityId: this.id,
            storeName: this.editFrom.storeName,
            storeAddress: this.editFrom.storeAddress,
            storePoi: this.editFrom.storePoi,
            storePhone: this.editFrom.storePhone,
            files: this.editFrom.files,
          };
          // this.editShow = false;
          if (this.type === "编辑") {
            storeEdit(parmas)
              .then((res) => {
                console.log(res);
                this.tag = true;
                this.editShow = false;
                Toast("操作成功！");
                this.getData();
              })
              .catch((e) => {
                this.tag = true;
                Toast(e.message || e.errMessage);
                this.editShow = false;
              });
          } else if (this.type === "新增") {
            console.log(this.editFrom);
            storeAdd({
              businessOpportunityId: this.id,
              storeName: this.editFrom.storeName,
              storeAddress: this.editFrom.storeAddress,
              storePoi: this.editFrom.storePoi,
              storePhone: this.editFrom.storePhone,
              files: this.editFrom.files,
            })
              .then((res) => {
                console.log(res);
                this.tag = true;
                this.editShow = false;
                Toast("新增成功");
                this.getData();
              })
              .catch((err) => {
                console.log(err);
                console.log("err");
                this.tag = true;
                this.editShow = false;
                console.log(" this.editShow");
                let { code, message } = err;
                if (code === 2001) {
                  this.actionP.title = "";
                  this.actionP.content = message;
                  this.actionP.confirmText = "确认合并";
                  this.actionP.cancelText = "取消合并";
                  this.actionP.showButtons = "operate";
                  this.type = 2;
                  this.$nextTick(() => {
                    this.$refs.actionPopup.open(this.actionP);
                  });
                } else if (code === 2003) {
                  console.log("err");
                  console.log(222);
                  this.actionP.title = "";
                  this.actionP.content = message;
                  this.actionP.showButtons = "back";
                  this.actionP.backText = "返回";
                  this.$nextTick(() => {
                    this.$refs.actionPopup.open(this.actionP);
                  });
                } else {
                  Toast(err.errMessage || err.message); //后端数据
                }
              });
          }
        })
        .catch((err) => {
          console.log(err);
          Toast({ message: err[0].message, position: "top" });
        });
    },
    // 确认转移
    transferSubmit() {
      console.log("this.value", this.value);
      this.$refs.transForm
        .validate()
        .then(() => {
          // 传递参数 要转移的店铺ID shopId 转入的商机ID targetBusinessOpportunityId
          storeTransfer({ shopId: 123, targetBusinessOpportunityId: 456 })
            .then(() => {
              Toast({ message: "店铺转移成功，等待对方接收" });
              this.value = "";
              this.transferShow = false;
            })
            .catch((err) => {
              Toast(err.errMessage || err.message);
            });
        })
        .catch((err) => {
          console.log("err", err);
          Toast({ message: err[0].message, position: "top" });
        });
    },
    back() {
      this.editShow = false;
    },
    edit(val, type) {
      this.editFrom = {};
      this.photoList = [];
      if (type === "编辑") {
        this.type === "编辑";
        this.title = "编辑店铺";
        this.$nextTick(() => {
          this.storeCheck(1, this.type, val);
        });
      } else if (type === "新增") {
        this.editShow = true;
        this.type === "新增";
        this.title = "新增店铺";
      }
    },
    storeDetail(val) {
      storeDetail({ id: val })
        .then((res) => {
          this.editFrom = res;
          console.log(this.editFrom);
          this.photoList = res.files.map((v) => {
            return { url: v.completeUrl };
          });
          console.log(this.photoList);
        })
        .catch((e) => {
          Toast(e.message || e.errMessage);
        });
    },
    // 获取商机列表
    storeBusinessOpportunity(searchKey) {
      storeBusinessOpportunity({ searchKey })
        .then((res) => {
          this.columns = res;
        })
        .catch((err) => {
          Toast(err.errMessage || err.message);
        });
    },
    onLoad() {
      setTimeout(() => {
        if (this.refreshing) {
          this.refreshing = false;
        }
        this.loading = false;
        this.finished = true;
      }, 500);
    },
    onRefresh() {
      this.finished = false;
      this.getData();
    },
    getData() {
      this.loading = true;
      this.refreshing = true;
      storeShop({ id: this.id })
        .then((res) => {
          this.refreshing = false;
          this.loading = false;
          this.list = res;
        })
        .catch((e) => {
          Toast(e.message || e.errMessage);
          this.refreshing = false;
          this.loading = false;
        });
    },
    _mapConfirm(poi) {
      this.editFrom.storeAddress = `${poi.pname}${poi.cityname}${poi.adname}${poi.address}(${poi.name})`;
      this.editFrom.storePoi = poi.id;
      console.log(this.editFrom);
      this.$nextTick(() => {
        this.showVisitLocation = false;
      });
    },
  },
  beforeDestroy() {
    Bus.$off("Details");
  },
};
</script>

<style lang="less" scoped>
.Detail_business {
  height: calc(100vh - 90px);
  padding-bottom: 10px;
  overflow: auto;
  .safePadding {
    padding-bottom: 50px;
    .end_field::after {
      border-bottom: 0;
    }
  }

  .van-action-sheet__header {
    text-align: left;
    line-height: normal;
    padding-top: 20px;
    padding-bottom: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    color: #333333;
    font-size: 16px;
    font-weight: 600;
    padding-left: 16px;
  }
  .add {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 98px;
    padding: 10px 14px 44px;
    background-color: #fff;
    .van-button {
      border-radius: 10px;
    }
  }

  .shopInfo-detail {
    .del,
    .trans {
      width: 100%;
      text-align: center;
      padding: 16px 0;
      color: #1d6fe9;
      border-top: 1px #eeeeee solid;
    }

    .info {
      padding-top: 16px;
      margin: 10px;
      background-color: #fff;
      border-radius: 8px;
      color: #666;
      font-size: 13px;
      .box {
        margin-top: 12px;
        margin-left: 12px;
        color: #666;
        display: flex;
        align-items: flex-start;
        .text {
          display: inline-block;
          max-width: 258px;
          color: #333333;
          word-wrap: break-word;
        }
        .name_text {
          white-space: nowrap;
        }
      }
      h4 {
        padding-right: 12px;
        border-bottom: 1px solid #f5f5f5;
        .name {
          font-size: 16px;
          font-weight: 600;
          color: #333;
          display: flex;
          align-items: center;
          flex-grow: 1;
          &:before {
            content: "";
            border-left: 4px solid #1d6fe9;
            margin-right: 8px;
            height: 12px;
            display: block;
          }
        }
        .van-button--mini {
          border-radius: 16px;
          border: 1px solid #1d6fe9;
          background-color: rgba(29, 111, 233, 0.1);
          padding: 4px 10px;
          .van-icon-edit:before {
            color: #1d6fe9;
            margin-right: 7px;
          }
          .van-button__text {
            color: #1d6fe9;
            font-size: 12px;
          }
        }
      }
      .van-button--mini {
        border: none;
        .van-button__text {
          color: #1d6fe9;
          font-size: 14px;
        }
      }
    }
  }
}
.business_bottom {
  height: calc(100vh - 190px - env(safe-area-inset-bottom));
}
</style>
<style lang="scss">
.edit_shop {
  .exist_value {
    .van-field__label {
      color: #999999 !important;
    }
    .van-field__control {
      color: #333;
    }
    .van-field__control:disabled {
      color: #333;
    }
    .van-field__value {
      color: #333 !important;
    }
    .van-field--disabled {
      .van-field__control {
        color: #333 !important;
      }
    }
    .van-field__control:disabled {
      -webkit-text-fill-color: #333;
    }
  }
  .opportunity_box {
    padding: 16px;
  }
}
</style>
